package main

import (
	"fmt"
	"net/http"
	"sync"
	"time"
)

const (
	routineCountTotalaa = 5 //限制线程数
)

// 2. 优雅一点, 限制线程池, 以master-worker的方式处理并发, 最后又把响应统一处理.
// master-worker形式

func main() {
	var numberTasks = [5]string{"13456755448", " 13419385751", "13419317885", " 13434343439", "13438522395"}
	client = &http.Client{}
	beg := time.Now()
	wg := &sync.WaitGroup{}
	tasks := make(chan string)
	results := make(chan string)
	// receiver接受响应并处理的函数块, 也可以单独写在一个函数
	go func() {
		for result := range results {
			if result == "" {
				close(results)
			} else {
				fmt.Println("result:", result)
			}
		}
	}()
	for i := 0; i < routineCountTotal; i++ {
		wg.Add(1)
		go worker(wg, tasks, results)
	}
	//分发任务
	for _, task := range numberTasks {
		tasks <- task
	}
	tasks <- ""   //worker结束标志
	wg.Wait()     //同步结束
	results <- "" // result结束标志
	fmt.Printf("time consumed: %fs", time.Now().Sub(beg).Seconds())
}

func worker(group *sync.WaitGroup, tasks chan string, result chan string) {
	for task := range tasks {
		if task == "" {
			close(tasks)
		} else {
			respBody, err := NumberQueryRequest(task)
			if err != nil {
				fmt.Printf("error occurred in NumberQueryRequest: %s\n", task)
				result <- err.Error()
			} else {
				result <- string(respBody)
			}
		}
	}
	group.Done()
}
